package cn.feizhu.aimarket.ai.workflow.node;

import cn.feizhu.aimarket.ai.workflow.model.constant.WorkflowControlConstant;
import cn.feizhu.aimarket.model.dto.ai.outline.NovelOutlineResponse;
import cn.hutool.json.JSONUtil;
import com.alibaba.cloud.ai.graph.OverAllState;
import com.alibaba.cloud.ai.graph.action.NodeAction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * 返回URL节点
 * 作为工作流的最终节点，返回可视化结果的访问链接和完整的处理结果
 *
 * @author feizhu
 * @since 2025/10/16
 */
public class ReturnUrlNode implements NodeAction {

    private static final Logger logger = LoggerFactory.getLogger(ReturnUrlNode.class);

    @Override
    public Map<String, Object> apply(OverAllState state) {
        logger.info("=== 返回URL节点开始执行 ===");

        try {
            // 获取可视化URL
            String visualUrl = (String) state.value(WorkflowControlConstant.VISUAL_URL)
                    .orElse("未生成可视化URL");

            // 获取用户原始输入
            String userInput = (String) state.value(WorkflowControlConstant.USER_INPUT)
                    .orElse("未知输入");

            // 获取处理过程中的关键信息 - 处理类型转换问题
            Object outlineObj = state.value(WorkflowControlConstant.OUTLINE).orElse(null);
            String outline;
            if (outlineObj == null) {
                outline = "未生成大纲";
            } else if (outlineObj instanceof String) {
                outline = (String) outlineObj;
            } else if (outlineObj instanceof NovelOutlineResponse) {
                // 将NovelOutlineResponse对象转换为JSON字符串
                outline = JSONUtil.toJsonPrettyStr(outlineObj);
            } else if (outlineObj instanceof Map) {
                // 如果是Map类型，转换为JSON字符串
                outline = JSONUtil.toJsonPrettyStr(outlineObj);
            } else {
                outline = "大纲数据类型不支持: " + outlineObj.getClass().getName();
            }

            String feedback = (String) state.value(WorkflowControlConstant.FEEDBACK)
                    .orElse("无反馈信息");

            logger.info("准备返回最终结果，可视化URL: {}", visualUrl);

            // 生成完整的处理结果摘要
            Map<String, Object> processingResult = generateProcessingResult(
                    userInput, outline, feedback, visualUrl);

            // 生成用户友好的响应消息

            logger.info("智能内容生成工作流执行完成");
            logger.info("最终访问 MinIO URL: {}", visualUrl);

            return Map.of(
                    WorkflowControlConstant.FINAL_URL, visualUrl,
                    WorkflowControlConstant.PROCESSING_RESULT, processingResult,
                    WorkflowControlConstant.WORKFLOW_STATUS, "COMPLETED"
            );

        } catch (Exception e) {
            logger.error("返回URL节点执行异常", e);
            return Map.of(
                    WorkflowControlConstant.FINAL_URL, "处理失败",
                    WorkflowControlConstant.RESPONSE_MESSAGE, "工作流执行异常：" + e.getMessage(),
                    WorkflowControlConstant.WORKFLOW_STATUS, "ERROR"
            );
        } finally {
            logger.info("=== 返回URL节点执行完成 ===");
        }
    }

    /**
     * 生成处理结果摘要
     */
    private Map<String, Object> generateProcessingResult(String userInput, String outline,
                                                        String feedback, String visualUrl) {
        return Map.of(
                "user_input", userInput,
                "outline_generated", !outline.equals("未生成大纲"),
                "feedback_received", !feedback.equals("无反馈信息"),
                "visualization_created", !visualUrl.equals("未生成可视化URL"),
                "completion_time", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),
                "workflow_steps", Map.of(
                        "smart_judge", "已完成",
                        "command_process", "已完成",
                        "outline_generate", "已完成",
                        "human_feedback", "已完成",
                        "multi_doc_generate", "已完成",
                        "aggregate", "已完成",
                        "visualization", "已完成",
                        "return_url", "进行中"
                )
        );
    }
}
